package com.qfedu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.common.core.entity.Weather;
import com.qfedu.mapper.TbWeatherMapper;
import com.qfedu.service.ITbWeatherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class TbWeatherServiceImpl extends ServiceImpl<TbWeatherMapper, Weather> implements ITbWeatherService {

    @Value("${spring.amap.key}")
    private String weatherApiKey;

    @Value("${spring.amap.city}")
    private String cityCode;

    @Override
    public List<Weather> getWeather() {
        // 查询最近3天的天气数据
        LambdaQueryWrapper<Weather> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Weather::getDate).last("LIMIT 3");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    @Scheduled(cron = "0 0/5 * * * ?") // 每5分钟执行一次，测试用
    public void importWeather() {
        log.info("~~~~~~~~开始执行天气数据导入定时任务~~~~~~~~~~");
        String requestURL = String.format("https://restapi.amap.com/v3/weather/weatherInfo?key=%s&city=%s&extensions=all&output=JSON",
                weatherApiKey, cityCode);

        try {
            // 1. 调用高德API获取天气数据
            String jsonResponse = getWeatherData(requestURL);
            log.info("高德API返回数据: {}", jsonResponse);

            JSONObject jsonObject = JSON.parseObject(jsonResponse);
            if (!"1".equals(jsonObject.getString("status"))) {
                String errorMsg = String.format("获取天气数据失败，状态码: %s, 信息: %s",
                        jsonObject.getString("infocode"), jsonObject.getString("info"));
                log.error(errorMsg);
                return;
            }

            // 2. 解析天气数据
            JSONArray forecasts = jsonObject.getJSONArray("forecasts");
            if (forecasts == null || forecasts.isEmpty()) {
                log.error("未获取到天气预报数据");
                return;
            }

            JSONObject forecast = forecasts.getJSONObject(0);
            JSONArray casts = forecast.getJSONArray("casts");
            List<Weather> weatherList = new ArrayList<>();

            for (int i = 0; i < casts.size(); i++) {
                JSONObject cast = casts.getJSONObject(i);
                Weather weather = new Weather();
                weather.setId(UUID.randomUUID().toString().replace("-", "").substring(0, 20));
                weather.setDate(cast.getString("date"));
                weather.setWeek(cast.getString("week"));
                weather.setDayweather(cast.getString("dayweather"));
                weather.setNightweather(cast.getString("nightweather"));
                weather.setDaytemp(cast.getString("daytemp"));
                weather.setNighttemp(cast.getString("nighttemp"));
                weather.setDaywind(cast.getString("daywind"));
                weather.setNightwind(cast.getString("nightwind"));
                weather.setDaypower(cast.getString("daypower"));
                weather.setNightpower(cast.getString("nightpower"));
                weather.setCreateDate(new Date());

                weatherList.add(weather);
                log.info("解析到的天气数据: {}", weather);
            }

            // 3. 先清空表再插入新数据（简单处理）
            baseMapper.delete(null); // 清空表

            // 4. 批量保存新数据
            boolean saveResult = saveBatch(weatherList);
            log.info("天气数据导入{}，共导入{}条数据",
                    saveResult ? "成功" : "失败", weatherList.size());

        } catch (Exception e) {
            log.error("天气数据导入定时任务执行失败", e);
        }
    }

    private String getWeatherData(String requestURL) throws IOException {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            URL url = new URL(requestURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.connect();

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new IOException("HTTP请求失败，状态码: " + responseCode);
            }

            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            String strRead;
            while ((strRead = reader.readLine()) != null) {
                stringBuilder.append(strRead);
            }

            return stringBuilder.toString();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}